<!DOCTYPE html>
{% load static %}
<html>
<head>
  <title>WebSocket Image</title>
  <meta charset="utf-8"/>
</head>
<body>
  <input type="file" id="imageInput" accept="image/*">
  <button id="sendButton">发送图片</button>

  <!-- Image container to display received images -->
  <div id="imageContainer"></div>

  <script>
    const socket = new WebSocket('ws://127.0.0.1/ws/chat/lobby/');

    socket.onmessage = function (e) {
        const data = JSON.parse(e.data);

        // 判断是否为图片消息
        if (data['type'] === 'image')
        {
            const imageFileName = data['message']; // 图片文件名
            const imageUrl = `http://127.0.0.1:8000/static/media/${imageFileName}`; // 构建图片访问地址
            // 创建一个新的图片元素
            const imageElement = document.createElement('img');
            imageElement.src = imageUrl;

            // 将图片元素添加到图片容器中
            const imageContainer = document.getElementById('imageContainer');
            imageContainer.appendChild(imageElement);
        }
    };


    socket.onopen = function (event) {
      console.log('WebSocket connection established.');
    };

    socket.onerror = function (error) {
      console.error('WebSocket error:', error);
    };

    socket.onclose = function (event) {
      console.log('WebSocket connection closed.');
    };

    // Handle image sending when the button is clicked
    document.getElementById('sendButton').addEventListener('click', function () {
      const inputElement = document.getElementById('imageInput');
      const file = inputElement.files[0];
      const reader = new FileReader();

      reader.onloadend = function () {
        // Get the Base64 encoded data
        const imageData = reader.result.split(',')[1];
        // Send the image data through WebSocket
        socket.send(JSON.stringify({
          'image': imageData,
          'username': '游客',
          'room': 'lobby',
          'type': 'image',
        }));

        console.log('发送成功！');
      };

      if (file) {
        reader.readAsDataURL(file);
      } else {
        console.error('Please select an image.');
      }
    });


    // ---------显示接收到的图片---------



  </script>
</body>
</html>
